﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NewAI.FSM
{

    public class FSMMessage
    {
        public event EventHandler<FSMEventEventArg> OnEvent;
        private int delagateCount = 0;
        private int hasCallCount = 0;
        private AsyncCallback finishCallback;

        public void Call(object sender = null, FSMEventEventArg args = null, AsyncCallback finishCallback = null)
        {
            if (OnEvent == null)
                return;
            Delegate[] delegates = OnEvent.GetInvocationList();
            delagateCount = delegates.Length;
            hasCallCount = 0;
            this.finishCallback = finishCallback;
            foreach (EventHandler<FSMEventEventArg> item in delegates)
            {
                try
                {
                    item.BeginInvoke(sender, args, OneDelegateCallFinish, null);
                }
                catch (Exception)
                {
                    hasCallCount++;
                    if (hasCallCount == delagateCount)
                        finishCallback.BeginInvoke(null, null, null);
                }
            }

        }

        private void OneDelegateCallFinish(IAsyncResult ar)
        {
            hasCallCount++;
            if (hasCallCount == delagateCount && finishCallback != null)
                finishCallback.BeginInvoke(null, null, null);

        }

    }
}
